


/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template
 */
package houduan ;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 *
 * @author 20204
 */
@WebServlet(name = "Post", urlPatterns = {"/Post"})
public class Post extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet UeditorServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet UeditorServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    private String getUserFromId(Integer userId) {
        if (userId!= null) {
            User user = LoginServlet.userSessionMap.get(userId);
            if (user!= null) {
                return user.getUsername();
            }
        }
        return null;
    }
    private static final long serialVersionUID = 1L;
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求和响应的编码统一为UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取当前登录用户的用户id（假设已经按前面提到的方式将会话标识userSessionId存储在会话中）
            Integer userSessionId = (Integer) request.getSession().getAttribute("userSessionId");
            if (userSessionId == null) {
                out.println("<html><body><h1>请先登录！</h1></body></html>");
                return;
            }
            
             // 根据用户id获取用户名（这里调用合适的方法去获取，假设已经有对应的方法实现）
            String author = getUserFromId(userSessionId);
            if (author == null) {
                out.println("<html><body><h1>获取用户信息失败，请联系管理员！</h1></body></html>");
                return;
            }

        // 获取帖子标题
        String title = request.getParameter("title");

        // 获取富文本编辑器中的内容
        String content = request.getParameter("editorValue");
        
        String category = request.getParameter("category");
        

        // 数据库连接相关配置（这里仅为示例，实际中配置应该更灵活和安全）
        String url = "jdbc:mysql://localhost:3306/lczmysql";
        String dbUsername = "root";
        String dbPassword = "123456";

        try {
            // 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接
            Connection connection = DriverManager.getConnection(url, dbUsername, dbPassword);
            // 准备插入帖子数据的SQL语句，注意这里根据你的表结构插入相应字段
            String sql = "INSERT INTO post (username, title, content,category) VALUES (?,?,?,?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, author);
            preparedStatement.setString(2, title);
            preparedStatement.setString(3, content);
            preparedStatement.setString(4, category);

            // 执行插入操作
            int rowsInserted = preparedStatement.executeUpdate();
            if (rowsInserted > 0) {
                // 修改此处，添加返回首页的链接
                out.println("<html><body><h1>帖子发布成功！<a href='./index.jsp'>返回首页</a></h1></body></html>");
            } else {
                out.println("<html><body><h1>帖子发布失败，请重试！</h1></body></html>");
            }

            // 关闭资源
            preparedStatement.close();
            connection.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            out.println("<html><body><h1>发生错误：" + e.getMessage() + "</h1></body></html>");
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
